const baseUrl = 'http://localhost:8080'
function api ({method, url, data, cookie}) {
    var xhr = new XMLHttpRequest()
    if (method == 'GET' && data) {
        url += '?' + Object.keys(data).map(key => key + '=' + data[key]).join('&')
    }
    xhr.open(method, baseUrl + url, true)
    if (cookie) {
        /**
         * 此处设置为true，表示允许携带cookie
         * 必须在xhr.open()之后设置，在xhr.send()之前设置
         * 携带的cookie是当前域名下的cookie,通过document.cookie获取的cookie
         */
        xhr.withCredentials = true
    }
    let token = localStorage.getItem('token')
    if (token) {
        xhr.setRequestHeader('Authorization', 'Bearer ' + token)
    }
    if (method == 'POST') {
        xhr.setRequestHeader('Content-Type', 'application/json')
        xhr.send(JSON.stringify(data))
    } else {
        xhr.send()
    }
    return new Promise((resolve, reject) => {
        xhr.onreadystatechange = function() {
            if (xhr.readyState == 4) {
                if (xhr.status == 200) {
                    let res = JSON.parse(xhr.responseText)
                    resolve(res)
                } else {
                    reject('请求失败')
                }
            }
        }
    })
}